package org.mch.swingm.core;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class MToggleButtonGroup extends MouseAdapter {

	private int selectedCount;
	private List<MToggleButton> buttonList = new ArrayList<MToggleButton>();

	public MToggleButtonGroup(int selectedCount) {
		super();
		this.selectedCount = selectedCount;
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		MToggleButton tBtn = (MToggleButton) e.getSource();

		if (e.getButton() == 3) {
			tBtn.setSelected(false);
			return;
		}

		int alreadyCount = 0;
		MToggleButton oldFirstBtn = null;

		for (int i = 0, len = buttonList.size(); i < len; i++) {
			MToggleButton tmp = buttonList.get(i);

			if (tmp.isSelected()) {
				alreadyCount++;
				if (oldFirstBtn == null && tmp != tBtn) {
					oldFirstBtn = tmp;
				}
			}
		}

		if (alreadyCount > selectedCount) {
			oldFirstBtn.setSelected(false);
		}
	}

	public int getSelectedCount() {
		return selectedCount;
	}

	public void addGroupButton(MToggleButton btn) {
		btn.addMouseListener(this);
		this.buttonList.add(btn);
	}
}
